const express = require('express')
const path = require('path')
const app = express()
const axios = require('axios')
const ejs = require('ejs')
const dotenv = require("dotenv") 
 
const URL = require("url")
const querystring = require("querystring")
const { resolve } = require('path')

dotenv.config()

const site_title = process.env.site_title
const API_URL = process.env.api_url
const publish_domain = process.env.publish_domain
app.engine('html', ejs.__express);
app.set('view engine', 'html');

// Routes
app.get(`/`, (req, res) => { 
 
  var arg = URL.parse(req.url).query;
	var params = querystring.parse(arg);

  params.publish_domain = publish_domain
  if (!params.limit) {
    params.limit = process.env.index_limit; 
  }
  
  //nodejs将数组组的key和值装成字符串，用"&“连接起来
  const query_string = Object.keys( params ).map( (key) => key + '=' + params[key]).join('&') 

  let site = {};
  site['title'] = process.env.site_title;
  site['keyword'] = process.env.site_keyword;
  site['description'] = process.env.site_description;

  const url = API_URL+'/lists'+"?"+query_string;
  axios.get(url).then((response)=>{     
   
      res.render(__dirname+'/views/index.html', {data:response.data.data,'site':site});
  }).catch((error)=>{
      console.log("error",error);
      // alert('服务器没有链接成功')
  })

  
})

 
app.get('/articles/:name', (req, res) => {
  filename=  req.params.name.replace(".html",'')
  const url = API_URL+'/single';
  postdata = {}
  postdata.shorttitle = filename
  postdata.publish_domain = publish_domain
 
  const query_string = Object.keys( postdata ).map( (key) => key + '=' + postdata[key]).join('&') 
 
  axios.get(url+"?"+query_string,{
    headers:{
      'Access-Control-Allow-Origin' : '*',
        'Content-Type': 'application/json'
    }
  })
  .then((response)=>{      
      if(response.data=='') {
        // res.render('404.html',{'title':site_title})
        res.status(404).send('Not found')
      } else {
        let site = {};
        site['keyword'] = response.data.keyword || process.env.site_keyword;
        site['description'] = response.data.shortdesc || process.env.site_description;
      
        res.render(__dirname+'/views/articles.html',{data:response.data[0],site:site})   
      }
  })
  .catch((error)=>{
      console.log(error.data);
      // alert('服务器没有链接成功')
  })
})



app.get('/lists.html', function(req, res, next) {
  var arg = URL.parse(req.url).query;
  var params = querystring.parse(arg);

  
  params.publish_domain = publish_domain
  try {
      if (!params.limit) {
        params.limit = 20; 
      } 

        //nodejs将数组组的key和值装成字符串，用"&“连接起来
        const query_string = Object.keys( params ).map( (key) => key + '=' + params[key]).join('&') 

        let site = {};
        site['title'] =   process.env.site_title;
        site['keyword'] =   process.env.site_keyword;
        site['description'] =   process.env.site_description;

        const url = API_URL+'/lists'+"?"+query_string;

        axios.get(url).then((response)=>{     
          // console.log("54 >>>")
           console.log(response)
            res.render(__dirname+'/views/lists.html', {data:response.data,'site':site});
        }).catch((error)=>{
            console.log("error",error);
            // alert('服务器没有链接成功')
        })
    }
    catch (error) {
      console.log(error.data);
         
    }

})



app.get('/category.html', function(req, res, next) {
  var arg = URL.parse(req.url).query;
  var params = querystring.parse(arg);
   
  params.publish_domain = publish_domain
  try {
      if (!params.limit) {         
         params.limit = 20 ;
      }
      if (!params.cate) {
         throw new Error('cate参数未输入');
      }
        //nodejs将数组组的key和值装成字符串，用"&“连接起来
        const query_string = Object.keys( params ).map( (key) => key + '=' + params[key]).join('&') 

        let site = {};
        site['title'] =   process.env.site_title;
        site['keyword'] =   process.env.site_keyword;
        site['description'] =   process.env.site_description;

        const url = API_URL+'/category'+"?"+query_string;

        axios.get(url).then((response)=>{     
          // console.log("54 >>>")
           console.log(response)
            res.render(__dirname+'/views/lists.html', {data:response.data,'site':site});
        }).catch((error)=>{
            console.log("error",error);
            // alert('服务器没有链接成功')
        })
    }
    catch (error) {
      console.log(error.data);
         
    }

})






app.use('/static', express.static('static'));


app.get('/404', (req, res) => {
  res.status(404).send('Not found')
})

app.get('/500', (req, res) => {
  res.status(500).send('Server Error')
})

// Error handler
app.use(function(err, req, res, next) {
  console.error(err)
  res.status(500).send('Internal Serverless Error')
})


app.listen(9000, () => {
  console.log(`Server start on http://localhost:9000`);
})
